<template>
  <div class="mod-config editViewContainer">
    <split-pane class="splitPane" :min-percent='10' :default-percent='10' split="vertical">
      <template slot="paneL">
        <div class="treeViewContainer">
          <tree-view ref="treeView" :treeData="statusTreeList" :checkChangedHandler="getDataList"></tree-view>
        </div>
      </template>
      <template slot="paneR">
        <table-view ref="view"
                    :searchAttrs="searchAttrs"
                    :primaryKey="primaryKey"
                    :listApiName="listApiName"
                    :deleteApiName="deleteApiName"
                    :saveAuthName="saveAuthName"
                    :deleteAuthName="deleteAuthName"
                    :showAttrs="showAttrs"
                    :optionWidth="200"
                    :exportAuthName="exportAuthName"
                    :exportPlantFunc="exportPlantFunc"
        >
          <template v-slot:foot="{scope}">

            <el-tooltip class="item" effect="dark" content="仅光瓶和拉管瓶可转"
                        placement="bottom" :hide-after="1800" :open-delay="800">
              <el-button type="text" size="small" @click="deepProductOrderDialog(scope.row)" >转深加工</el-button>
            </el-tooltip>
          </template>
        </table-view>
      </template>

    </split-pane>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <el-dialog
      title="制定商品采购合同"
      :visible="purchaseContractVisible"
      width="80%">

      <el-form
        ref="dataForm"
        label-width="120px"
        label-position="left"
        style="margin-left:30px"
      >

        <el-form-item label="供应商" style="width: 400px">
          <el-select v-model="supplierId" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in supplierList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label=采购时间 style="width: 400px">
          <el-date-picker
            v-model="contractTime"
            align="right"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label=交货时间 style="width: 400px">
          <el-date-picker
            v-model="deliveryTime"
            align="right"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label=总金额 style="width: 400px">
          <el-input-number controls-position="right" size="small" :min="0"  v-model="totalAmount"  disabled placeholder="数量"></el-input-number>
        </el-form-item>
        <el-form-item label=付款周期>
          <el-radio-group v-model="paymentCycle" >
            <el-radio :label="0" border>月结</el-radio>
            <el-radio :label="1" border>款到发货</el-radio>
            <el-radio :label="2" border>3个月账期</el-radio>
            <el-radio :label="3" border>付30%定金，余款70%款到发货</el-radio>
            <el-radio :label="4" border>2个月账期</el-radio>

          </el-radio-group>
        </el-form-item>
      </el-form>

      <el-table
        :data="tableListData"
        border
        style="display: inline-block">
        <el-table-column
          prop="id"
          label="订单编号"
          align="center"
          width="200"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.orderDetailId" clearable filterable placeholder="请选择"  >
              <el-option
                v-for="item in orderDetailList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>


        <el-table-column
          prop="id"
          label="商品信息"
          align="center"
          width="230"
        >
          <template slot-scope="scope">
            <el-select v-model="scope.row.productId" clearable filterable placeholder="请选择"  >
              <el-option
                v-for="item in sysDictList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-table-column>

        <el-table-column
          prop="unitPrice"
          label="单价"
          width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0" @change="calculateTotalAmount"  v-model="scope.row.unitPrice"  placeholder="价格"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="purchaseNumber"
          label="数量"
          width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-input-number controls-position="right" size="small" :min="0" @change="calculateTotalAmount"  v-model="scope.row.purchaseNumber"  placeholder="数量"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column
          prop="taxInclusive"
          label="是否含税"
          width="140"
          align="center"
        >
          <template slot-scope="scope">
            <el-radio-group v-model="scope.row.taxInclusive">
              <el-radio :label=0>不含</el-radio>
              <el-radio :label=1>含税</el-radio>
            </el-radio-group>
          </template>
        </el-table-column>

        <el-table-column
          prop="customerRequire"
          label="规格描述"
          align="center"
        >
          <template slot-scope="scope">
              <el-input  size="small"  v-model="scope.row.customerRequire"  placeholder="规格描述"></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          align="center"
        >
          <template slot-scope="scope">
            <el-input type="textarea" controls-position="right" size="small" :min="0"  v-model="scope.row.remark" placeholder="备注"></el-input>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="purchaseContractVisible = false">取 消</el-button>
        <el-button type="primary" @click=savePurchaseContractAndUpdatePartStatus>确 定</el-button>
      </span>

    </el-dialog>

    <el-dialog
      title="光瓶和拉管瓶转深加工"
      :visible.sync="orderTimeLineVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      width="50%">
      <div class="block">
        <template v-for="(item, index) in productDeepCategoryList">
          <div :key="index" style="display: flex;position: relative; margin-top: 5px; width: 97%">
            <el-select v-model="item['deepCategoryIdList']" filterable clearable multiple
                       style="margin-right: 5px;" placeholder="请选择深加工工艺">
              <el-option v-for="item in deepCategoryList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>

            <el-input v-model="item['customerRequire']" placeholder="工艺描述"

                      style="margin-right: 5px;"></el-input>

            <el-input-number v-model="item['purchaseNumber']" placeholder="采购数量"
                             type="number"
                             style="margin-right: 5px;"></el-input-number>

            <el-tooltip class="item" effect="dark" content="新增"
                        placement="bottom">
              <a class="el-icon-circle-plus-outline" @click="addOneLine(index+1)"
                 style="position: absolute;right: -17px; top: 10px;"></a>
            </el-tooltip>
            <el-tooltip v-if="productDeepCategoryList.length > 1" class="item" effect="dark" content="删除" placement="bottom">
              <a class="el-icon-remove-outline" @click="deleteOneLine(index)"
                 style="position: absolute;right: -35px; top: 10px;"></a>
            </el-tooltip>
          </div>
        </template>
        <div class="ScreenShot" >
          <label >深加工样图</label>
          <div v-show="!show" class="pasteInputDiv" @paste="handlePaste">
            <input type="text" class="pasteInput" autosize
                   placeholder="请粘贴深加工图片" maxlength="0">
          </div>
          <div v-if="show" class="pasteImgDiv">
            <i class="el-icon-error close-position"  @click="deleteImg" />
            <el-image
              class="pasteImg"
              :src="url"
              fit="fill"
              :z-index="99999"
            >
            </el-image>
          </div>
        </div>
      </div>


      <span slot="footer" class="dialog-footer">
        <el-button @click="orderTimeLineVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateContractOrderByDeep">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
import tableView from '@/components/tableView'
import basicMixins from '@/utils/commonViewMixins'
import AddOrUpdate from './purchasepart-add-or-update'
import treeView from '@/components/treeView'
import {mRequest} from '@/utils/request'
import {exportHandle, isAuth} from '@/utils'
import NormalListAndNumber from '@/components/normalForm/inputs/listAndNumber.vue'
import NormalListAndNumberAndRadio from '@/components/normalForm/inputs/listAndListAndInputAndNumber.vue'
import {API_DEFAULT_CONFIG} from '@/config'

export default {
  mixins: [basicMixins],
  data() {
    return {
      show: false,
      deepProductImage: '',
      contractOrderId: '',
      contractNo: '',
      clientId: '',
      productId: '',
      productNo: '',
      url: '',
      urlAttr: [],
      file: null,
      statusTreeList: [],
      productDeepCategoryList:[{deepCategoryIdList:[],customerRequire:'', purchaseNumber: 0}],
      primaryKey: 'id',
      listApiName: 'purchaseApi/listPurchasePartList',
      deleteApiName: 'purchaseApi/deletePurchasePart',
      saveAuthName: 'purchase:purchasepart:save',
      deleteAuthName: 'purchase:purchasepart:delete',
      exportAuthName: 'purchase:purchasepart:save',
      searchAttrs: {
        clientContractNo: {
          placeholder: '请输入业务合同号',
        },
        productNo: {
          placeholder: '请输入商品编号',
        },
        createUser: {
          label: '业务',
          clearable: true,
          type: 'autoComplete',
          placeholder: '请选择申请人',
          querySearchApiName: 'systemApi/listSaleUser'
        },
        supplierId: {
          label: '供应商名称',
          clearable: true,
          type: 'autoComplete',
          placeholder: '请输入供应商名称',
          querySearchApiName: 'supplierApi/getSupplierList'
        },
        status: {
          label: '状态',
          clearable: true,
          type: 'autoComplete',
          placeholder: '采购状态',
          querySearchApiName: 'systemApi/getSystemPurchaseStatusList'
        },
        dateTimeRange: {
          type: 'date',
          dateType: 'daterange',
          clearable: true
        },

        productCategoryId: {
          type: 'func',
          dataFunc: () => {
            return this.$refs.treeView.$refs.treeForm.getCheckedKeys()[0]
          }
        }
      },
      showAttrs: {
        supplierName: {
          label: '供应商',
          width: 140,
        },
        userName:{
          label: '申请人'
        },
        clientContractNo: {
          label: '业务合同',
          width: 140,
        },
        productNo: {
          label: '商品信息',
          width: 140,
          type: 'linkLabel',
          searchKey: 'productNo',
          routerName: 'product-product-info-all'
        },
        purchaseType: {
          label: '采购类型',
          type: 'radio',
          width: 110,
          items: [
            {value: 1, text: '光瓶',tagType:'success'},
            {value: 23, text: '纸箱',tagType: 'danger'},
            {value: 25, text: '礼盒',tagType: 'danger'},
            {value: 3, text: '喷头',tagType: 'success'},
            {value: 4, text: '中套'},
            {value: 5, text: '披肩',tagType: 'warning'},
            {value: 6, text: '塑料盖',tagType:'warning'},
            {value: 7, text: '锌合金盖',tagType:'danger'},
            {value: 8, text: '香薰棒',tagType:'danger'},
            {value: 9, text: '树脂盖',tagType:'success'},
            {value: 11, text: '深加工',tagType:'danger'},
            {value: 66, text: '滚珠',tagType:'info'},
            {value: 77, text: '电化铝盖',tagType:'warning'},
            {value: 88, text: '软管类',tagType:'info'},
            {value: 99, text: '其它',tagType:'danger'},
            {value: 100, text: '配件'},
            {value: 111, text: '拉管玻璃瓶'},
            {value: 999, text: '标牌',tagType:'info'},
            {value: 666, text: '木头竹子盖'},
            {value: 888, text: '膏霜罐'},
            {value: 8888, text: '小喷雾乳液泵',tagType:'success'},
            {value: 88888, text: '香水樽',tagType:'warning'},
            {value: 888888, text: '塑料瓶'},
          ]
        },
        customerRequire:{
          label: '规格描述',
          width: 170
        },
        businessRemark: {
          label: '业务订单备注',
          width: 200
        },
        remark: {
          label: '备注',
          width: 200
        },
        unitPrice: {
          label: '价格'
        },
        taxInclusive: {
          label: '含税价',
          type: 'radio',
          items: [
            {value: 0, text: '不含税'},
            {value: 1, text: '含税'}
          ]
        },
        sampleImage: {label: '采购图片', type: 'image'},
        imagePath: {
          label: '图片', type: 'image'
        },
        purchaseNumber: {
          label: '采购数量'
        },
        putInStorageNumber:{
          label: '入库数量'
        },
        totalPrice: {
          label: '总价'
        },
        status: {
          label: '状态',
          type: 'radio',
          items: [
            {value: -5, text: '采购退回', tagType: 'warning'},
            {value: 0, text: '待采购', tagType: 'info'},
            {value: 2, text: '采购进行中'},
            {value: 3, text: '采购逾期预警',tagType:'warning'},
            {value: 4, text: '采购已逾期', tagType: 'danger'},
            {value: 5, text: '货已完工'},
            {value: 6, text: '采购暂停', tagType: 'info'},
            {value: 7, text: '入库进行中',tagType: 'warning'},
            {value: 8, text: '入库完成',tagType: 'success'},
            {value: 15, text: '入库完成-其它库',tagType: 'success'},
            {value: 17, text: '挑选', tagType: 'warning'},
            {value: 18, text: '合格', tagType: 'success'},
            {value: 19, text: '不合格', tagType: 'danger'},
            {value: 20, text: '特采', tagType: 'warning'},
            {value: 99, text: '采购取消', tagType: 'danger'},
          ]
        },
        createTime: {
          label: '采购时间',
          type: 'date', width: 100
        },
        purchaseEndTime: {
          label: '交货时间',
          type: 'date', width: 100
        },
        productWeight:{
          label: '克重'
        },
        productVolume:{
          label: '容量'
        },
        strawLength:{
          label: '吸管长度'
        },
        orderNo: {
          label: '订单'
        },

        contractPurchaseNo: {
          label: '采购合同',
          type: 'linkLabel',
          routerName: 'contract-contractpurchaseinfo',
          searchKey: 'purchaseContractNo'
        }
      },
      purchaseContractVisible: false,
      orderTimeLineVisible: false,
      supplierList: [],
      deepCategoryList: [],
      sysDictList: [],
      orderDetailList: [],
      supplierId: '',
      contractTime: '',
      deliveryTime: '',
      paymentCycle: 0,
      totalAmount: 0,
      purchaseType: 14,
      remark: '',
      tableListData: [],
    }
  },
  components: {
    NormalListAndNumberAndRadio,
    NormalListAndNumber,
    treeView,
    tableView,
    AddOrUpdate
  },
  computed: {
    /**
     * @return {string}
     */
    URL() {
      return `${this.imageUrl}${this.urlAttr}?token=${this.token}`
    },
    token() {
      return this.$cookie.get('token')
    },
    imageUrl() {
      return `${API_DEFAULT_CONFIG.baseURL}/pub`
    },
    srcList() {
      return [`${this.imageUrl}${this.urlAttr}?token=${this.token}`]
    }
  },
  watch:{
    url() {
      if (this.url === '') {
        this.show = false
        this.urlAttr = []
      } else {
        this.show = true
      }
    },
    attrUrl: {
      handler() {
        if (this.R.isNil(this.attrUrl) || this.R.equals('', this.attrUrl.trim())) {
          this.url = null
        } else {
          this.url = `${API_DEFAULT_CONFIG.baseURL}/pub/${this.attrUrl}?token=${this.token}`
        }
      },
      deep: true
    }
  },
  methods: {
    deepProductOrderDialog(order) {
      console.log(order)
      this.productDeepCategoryList = [{deepCategoryIdList: [], customerRequire: '', purchaseNumber: 0}]
      this.deepProductImage = ''
      this.orderTimeLineVisible = true

      this.contractOrderId = order.contractOrderId
      this.contractNo = order.contractNo
      this.clientId = order.clientId
      this.productId = order.productId
      this.productNo = order.productNo
    },
    calculateTotalAmount() {
      this.totalAmount=0
      for (let i = 0; i <this.tableListData.length ; i++) {
        this.tableListData[i].totalPrice = this.tableListData[i].unitPrice * this.tableListData[i].purchaseNumber
        this.totalAmount += this.tableListData[i].totalPrice
      }
    },

    statusTreeListInit() {
      mRequest('productApi/getProductCategoryListByUser', {}, (res) => {
        const statusTreeList = this.R.pathOr([], ['data', 'list'], res)
        const productCategoryTreeList = [{
          id: '',
          name: '产品类别列表',
          nodeType: 0,
          children: []
        }]
        productCategoryTreeList[0].children = statusTreeList
        this.statusTreeList = productCategoryTreeList;
      })
      this.initDeepCategoryList()
    },
    // TODO 待晚上只有采购状态为0可以下单
    exportPlantFunc(rows){
      this.supplierId = ''
      this.contractTime = ''
      this.deliveryTime = ''
      this.purchaseType = ''
      this.remark = ''
      this.purchaseContractVisible = true
      this.initOrderDetailList()
      this.initSupplierList()
      this.initSysDictList()
      this.tableListData = rows
      this.calculateTotalAmount()
    },
    addOneLine(index) {
      const item = {deepCategoryIdList:[],customerRequire:'', purchaseNumber: 0}

      this.productDeepCategoryList.splice(index, 0, item)
    },
    deleteOneLine(index) {
      this.productDeepCategoryList.splice(index, 1)
    },
    initSupplierList() {
      mRequest('supplierApi/getSupplierList', {}, (res) => {
        this.supplierList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initOrderDetailList() {
      mRequest('orderApi/getOrderDetailList', {}, (res) => {
        this.orderDetailList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initSysDictList() {
      mRequest('productApi/getProductInfoList', {}, (res) => {
        this.sysDictList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    initDeepCategoryList(attrName = '') {
      mRequest('deepApi/deepCategoryList', {}, (res) => {
        this.deepCategoryList = this.R.pathOr([], ['data', 'list'], res)
      })
    },
    savePurchaseContractAndUpdatePartStatus(){
      if (this.R.isNil(this.supplierId) || this.R.isEmpty(this.supplierId)) {
        this.$message.error('请选择供应商')
        return
      }
      if (this.R.isNil(this.contractTime) || this.R.isEmpty(this.contractTime)) {
        this.$message.error('请选择合同时间')
        return
      }
      if (this.R.isNil(this.deliveryTime) || this.R.isEmpty(this.deliveryTime)) {
        this.$message.error('请选择交货时间')
        return
      }
      mRequest('contractApi/savePurchaseContractAndUpdatePartStatus', {
        'supplierId': this.supplierId,
        'contractTime': this.contractTime,
        'deliveryTime': this.deliveryTime,
        'purchaseType': this.purchaseType,
        'totalAmount': this.totalAmount,
        'paymentCycle': this.paymentCycle,
        'tableListDataBottleCap': this.tableListData
      }, (res => {
        let data = res.data
        if (data && data.code == 0) {
          let contractPurchaseInfo=data.contractPurchaseInfo
          this.$confirm('是否直接导出改计划?', '提示', {
            confirmButtonText: '导出',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            exportHandle('contractApi/getPurchasePartContractExport', {'contractPurchaseId': contractPurchaseInfo.id})
          }).catch(() => {
          })
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.purchaseContractVisible = false
              this.getDataList()
              this.$emit('refreshDataList')
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      }))
    },
    updateContractOrderByDeep() {
      mRequest("contractApi/updateContractOrderByDeep2", {
        'deepProductImage': this.deepProductImage,
        'contractNo': this.contractNo,
        'contractOrderId': this.contractOrderId,
        'clientId': this.clientId,
        'productId': this.productId,
        'productNo': this.productNo,
        'productDeepCategoryList': this.productDeepCategoryList
      }, (res => {
        let data = res.data
        if (data && data.code == 0) {

          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.orderTimeLineVisible = false
              this.getDataList()
              this.$emit('refreshDataList')
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      }))
    },

    handlePaste(event) {
      const items = (event.clipboardData || event.originalEvent.clipboardData).items;
      let file = null
      if (!items || items.length === 0) {
        this.$message.error('当前浏览器不支持本地')
        return
      }
      // 搜索剪切板items
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          file = items[i].getAsFile()
          break
        }
      }
      if (!file) {
        this.$message.error('粘贴内容非图片')
        return
      }
      // 此时file就是我们的剪切板中的图片对象
      const reader = new FileReader()
      reader.onload = (event) => {
        this.show = true
        this.uploadImageBase( event.target.result)
      }
      reader.readAsDataURL(file)
      this.$emit('imgFile', file)
      this.file = file
    },
    deleteImg() {
      this.url = ''
      this.show = false
      this.$emit('imgFile', '')
      this.$emit('imgBase64', '')
    },
    uploadImageBase(value) {
      mRequest('systemApi/uploadImageBase', {'imageBase': value}, (res) => {
        this.urlAttr = this.R.pathOr([], ['data', 'imageUrl'], res)
        this.url= `${this.imageUrl}${this.urlAttr}?token=${this.token}`
        this.deepProductImage = this.urlAttr
      })
    },
  },
  mounted() {
    this.statusTreeListInit()
  }
}
</script>
<style scoped>
.ScreenShot{
  margin-top: 10px;}
.pasteInputDiv{
  box-sizing: border-box;
  width: 158px;
  height: 158px;

}
.pasteInput{
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  height: 158px;
  line-height: 156px;
  vertical-align: top;
  width: 158px;
  font-size: 19px;
}
.pasteInput:hover{
  cursor: pointer;
  border: 1px dashed #409EFF;
}
.pasteImgDiv{
  position: relative;
  width: 158px;
  height: 158px;
}
.pasteImg{
  position: relative;
  width: 158px;
  height: 158px;
  border: 1px solid #c0ccda ;
  border-radius: 5px;
}
.close-position{
  position: absolute;
  right: -10px;
  top: -10px;
  font-size: 22px;
  background: #fff;
  border-radius: 50%;
  color: red;
  font-weight: bold;
  z-index: 9999;
}
.close-position:hover{
  cursor: pointer;
}
</style>

